package com.dcits.business.server.linux;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dcits.business.server.BaseServerController;
import com.dcits.business.userconfig.UserSpace;
import com.dcits.constant.ConstantReturnCode;
import com.dcits.tool.StringUtils;
import com.dcits.tool.ssh.SSHUtil;



public class LinuxServerController extends BaseServerController {
	public static final Logger logger = Logger.getLogger(LinuxServerController.class);
	
	
	/**
	 * 中断命令执行
	 */
	public void breakCommand() {
		SSHUtil.stopExecCommand(getPara("tag"));
		renderSuccess(null, "成功发送停止命令!");
	}
	
	/**
	 * 执行命令
	 */
	public void execCommand() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		String ids = getPara("viewIds");
		final String tag = getPara("tag");
		final String command = getPara("command");
			
		final JSONArray returnArr = new JSONArray();
		
		for (String id:ids.split(",")) {
			final LinuxServer server = (LinuxServer) space.getServerInfo(LinuxServer.SERVER_TYPE_NAME, Integer.valueOf(id));
			if (server == null) continue;
			final JSONObject obj = new JSONObject();
			obj.put("host", (StringUtils.isEmpty(server.getRealHost()) ? server.getHost() : server.getRealHost()) + "[" + server.getTags() + "]");
			Thread t = new Thread(new Runnable() {				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						long begin = System.currentTimeMillis();
						String returnInfo = SSHUtil.execCommand(server.getConn(), command, 999999, 2, tag);
						long end = System.currentTimeMillis();
						obj.put("returnInfo", returnInfo);
						obj.put("useTime", (end - begin));
					} catch (Exception e) {
						// TODO: handle exception
						logger.error(obj.get("host").toString() + " 命令执行失败:" + command, e);
						obj.put("returnInfo", "命令执行失败:" + e.getMessage());
						obj.put("useTime", 0);
					}
					returnArr.add(obj);
				}
			});
			t.start();
			try {
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		renderSuccess(returnArr, "命令执行成功!");
		
/*		try {
			long begin = System.currentTimeMillis();
			String returnInfo = SSHUtil.execCommand(server.getConn(), getPara("command"), 999999, 2, getPara("tag"));
			long end = System.currentTimeMillis();
			renderSuccess(setData("returnInfo", returnInfo).setData("useTime", (end - begin)), "命令执行成功!");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error(server.getHost() + ":" + server.getPort() + "命令执行失败:" + getPara("command"), e);
			renderError(ConstantReturnCode.SYSTEM_ERROR, "命令执行失败:" + e.getMessage());
		}*/
	}

	/**
	 * 检查当前主机上的java进程号
	 */
	public void checkJps() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		LinuxServer linux = (LinuxServer) space.getServerInfo(LinuxServer.SERVER_TYPE_NAME, getParaToInt("viewId"));
		
		String javaHome = getPara("javaHome");
		if (StringUtils.isNotEmpty(linux.getParameters()) && StringUtils.isEmpty(javaHome)) {
			LinuxExtraParameter parameter = JSONObject.parseObject(linux.getParameters(), new TypeReference<LinuxExtraParameter>(){});
			javaHome = parameter.getJavaHome();
		}
		
		if (StringUtils.isEmpty(javaHome) && "root".equalsIgnoreCase(linux.getUsername())) {
			javaHome = linux.parseJavaHome();
		}
		
		String processes = "";
		try {
			processes = linux.checkJps(javaHome);
		} catch (Exception e) {
			// TODO: handle exception
			processes = "执行jps命令出错,请检查javaHome是否设置正确:" + e.getMessage();
		}		
		
		renderSuccess(setData("viewId", linux.getViewId()).setData("javaHome", javaHome)
				.setData("processes", StringUtils.isEmpty(processes) ? "没有查询到该主机上的java进程列表,请检查javaHome是否设置正确或者当前账号的权限" : processes)
				, "加载成功!");
	}
}
